import logging, pathlib

from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

from protolib.gui_utils.pyqt5_messageboxes import show_critical_messagebox

from windows.to_protolib.console import ConsoleWindow
from windows.configure import ConfigureWindow

from widgets.file_browser import FileBrowserWidget

from config import load_config

logger = logging.getLogger(__name__)

class MainWindow(QMainWindow):
    def __init__(self, args):
        super().__init__()

        self.setWindowIcon(QIcon('icon.png'))
        self.setWindowTitle("File Browser")
        self.setMinimumWidth(700)
        self.setMinimumHeight(400)

        self.console = ConsoleWindow.new_window('Console - File Browser')

        #region
        menuBar = self.menuBar()
        #region
        self.fileMenu = QMenu("&File", self)
        menuBar.addMenu(self.fileMenu)
        #region
        refreshAction = QAction("&Refresh", self)
        refreshAction.setShortcut("Ctrl+R")
        refreshAction.setStatusTip('Update the directory listing')
        refreshAction.triggered.connect(lambda: self.get_tab().update_treeview())
        self.fileMenu.addAction(refreshAction)
        #endregion
        #region
        refreshAction = QAction("&Go To Parent", self)
        refreshAction.setShortcut("Ctrl+Up")
        refreshAction.setStatusTip('Go to the parent directory')
        refreshAction.triggered.connect(lambda: self.get_tab().goto_dir_parent())
        self.fileMenu.addAction(refreshAction)
        #endregion
        self.fileMenu.addSeparator()
        #region
        quitAction = QAction("&Quit", self)
        quitAction.setShortcut("Ctrl+Q")
        quitAction.setStatusTip('Leave the app')
        quitAction.triggered.connect(self.close)
        self.fileMenu.addAction(quitAction)
        #endregion
        #endregion
        #region
        self.editMenu = QMenu("&Edit", self)
        menuBar.addMenu(self.editMenu)
        #region
        copyAction = QAction("&Copy", self)
        copyAction.setStatusTip('Copy the selected file')
        copyAction.triggered.connect(lambda: self.get_tab().copy_path())
        copyAction.setShortcut('Ctrl+C')
        self.editMenu.addAction(copyAction)
        #endregion
        #region
        cutAction = QAction("&Cut", self)
        cutAction.setStatusTip('Cut the selected file')
        cutAction.triggered.connect(lambda: self.get_tab().copy_path())
        cutAction.setShortcut('Ctrl+X')
        self.editMenu.addAction(cutAction)
        #endregion
        #region
        pasteAction = QAction("&Paste", self)
        pasteAction.setStatusTip('Paste the file in your clipboard')
        pasteAction.triggered.connect(lambda: self.get_tab().copy_path())
        pasteAction.setShortcut('Ctrl+V')
        self.editMenu.addAction(pasteAction)
        #endregion
        self.editMenu.addSeparator()
        #region
        configureAction = QAction("&Config", self)
        configureAction.setStatusTip('Open the config menu')
        configureAction.triggered.connect(self.open_configure_window)
        self.editMenu.addAction(configureAction)
        #endregion
        #region
        self.hiddenFilesAction = QAction("Hidden Files", self, checkable=True)
        self.hiddenFilesAction.setStatusTip('Enable or disable removing hidden files from the directory listing')
        self.editMenu.addAction(self.hiddenFilesAction)
        #endregion
        #endregion
        #region
        self.consoleMenu = QMenu("&Console", self)
        menuBar.addMenu(self.consoleMenu)
        #region
        showConsoleAction = QAction("&Show", self)
        showConsoleAction.setStatusTip('Show the console window')
        showConsoleAction.triggered.connect(self.console.show)
        self.consoleMenu.addAction(showConsoleAction)
        #endregion
        #region
        hideConsoleAction = QAction("&Hide", self)
        hideConsoleAction.setStatusTip('Hide the console window')
        hideConsoleAction.triggered.connect(self.console.hide)
        self.consoleMenu.addAction(hideConsoleAction)
        #endregion
        #endregion
        #endregion

        #region
        layout = QVBoxLayout()
        widget = QWidget()
        widget.setLayout(layout)

        self.new_tab_button = QPushButton('New Tab')
        self.new_tab_button.clicked.connect(self.new_tab)

        self.tab_widget = QTabWidget()
        self.tab_widget.setCornerWidget(self.new_tab_button)
        layout.addWidget(self.tab_widget)

        self.new_tab()

        self.setCentralWidget(widget)
        #endregion

        logger.info('Main window initialized')

    def open_configure_window(self):
        tab = self.get_tab()
        window = ConfigureWindow(tab)
        window.exec_()
        tab.update_treeview()
        self.sync_browser_configs()

    def new_tab(self):
        file_browser = FileBrowserWidget()
        load_config(file_browser)
        self.hiddenFilesAction.toggled.connect(file_browser.update_hide_files)
        tab = self.tab_widget.addTab(file_browser, 'Placeholder')
        remove_tab_button = QPushButton('Close Tab')
        remove_tab_button.clicked.connect(lambda: self.close_tab(tab))
        self.tab_widget.tabBar().setTabButton(tab, 1, remove_tab_button)
        file_browser.directory_listing_refreshed.connect(lambda: self.update_tab_name(tab))
        file_browser.update_treeview()
        self.update_tab_name(tab)

    def update_tab_name(self, index):
        widget = self.tab_widget.widget(index)
        path = widget.get_current_path()
        if path.name:
            self.tab_widget.setTabText(index, path.name)
        else:
            self.tab_widget.setTabText(index, str(path))

    def get_tab(self) -> FileBrowserWidget:
        index = self.tab_widget.currentIndex()
        return self.tab_widget.widget(index)

    def close_tab(self, index):
        self.tab_widget.removeTab(index)
        if self.tab_widget.count() == 0:
            self.new_tab()

    def sync_browser_configs(self):
        cur_tab = self.get_tab()
        index = self.tab_widget.currentIndex()
        for i in range(self.tab_widget.count()):
            if i == index:
                continue
            tab = self.tab_widget.widget(i)
            tab.pattern_assoc = cur_tab.pattern_assoc
            tab.name_assoc = cur_tab.name_assoc
            tab.viewer_assoc = cur_tab.viewer_assoc
            tab.mimetype_assoc = cur_tab.mimetype_assoc

    def closeEvent(self, event):
        self.console.close()
        QMainWindow.closeEvent(self, event)
        logger.info('Main window closed')
